import sys
sys.path.append("../")

from types import NoneType

from view.Main_view import *
from Host_controller import *
from Distribution_controller import *
from Architecture_controller import *
from Office_controller import *
from Template_controller import *
from model.tables import *
from model.configuration import *
import logModule
class Main_controller(Ui_Main_view):

    def __init__(self):
        self.MainWindow = QtGui.QMainWindow()
        self.setupUi(self.MainWindow)
        self.refresh_table_offices()
        self.refresh_table_hosts()
        self.refresh_table_templates()
        self.change_grid_view()
        # Conectar los botones con funciones del dialogo.
        self.MainWindow.connect(self.actionAdd_Host, 
                                QtCore.SIGNAL("triggered()"), 
                                self.show_add_host
                                )
        self.MainWindow.connect(self.actionAdd_Distribution,
                                QtCore.SIGNAL("triggered()"),
                                self.show_add_distribution
                                )
        self.MainWindow.connect(self.actionAdd_Architecture,
                                QtCore.SIGNAL("triggered()"),
                                self.show_add_architecture
                                )
        self.MainWindow.connect(self.actionAdd_Office,
                                QtCore.SIGNAL("triggered()"),
                                self.show_add_office
                                )
        self.MainWindow.connect(self.actionAdd_Template,
                                QtCore.SIGNAL("triggered()"),
                                self.show_add_template
                                )
        self.MainWindow.connect(self.comboBoxView,
                                QtCore.SIGNAL("currentIndexChanged(int)"),
                                self.change_grid_view
                                )
        self.MainWindow.connect(self.pushButtonRefreshCache,
                                QtCore.SIGNAL("clicked()"),
                                self.refreshPackagesInfo
                                )
        self.MainWindow.connect(self.pushButtonDelete,
                                QtCore.SIGNAL("clicked()"),
                                self.delete
                                )
        self.MainWindow.connect(self.pushButtonAdd,
                                QtCore.SIGNAL("clicked()"),
                                self.add
                                )
        self.MainWindow.connect(self.pushButtonEdit,QtCore.SIGNAL("clicked()"),
                                self.edit)
        self.MainWindow.connect(self.pushButtonApplyChanges,
                                QtCore.SIGNAL("clicked()"), self.applyChanges)

    def delete(self):
        comboSelection = self.comboBoxView.currentText()
        if comboSelection == "Hosts":
           hostname = str(
                      self.tableHost.item(self.tableHost.currentRow(),0).text()
                      )
           hostcontroller = Host_controller()
           hostcontroller.deleteHost(hostname)
           self.tableHost.removeRow(self.tableHost.currentRow())
        elif comboSelection == "Templates":
           template = str(
              self.tableTemplate.item(self.tableTemplate.currentRow(),0).text()
              )
           templatecontroller = Template_controller()
           templatecontroller.deleteTemplate(template)
           self.tableTemplate.removeRow(self.tableTemplate.currentRow())
        elif comboSelection == "Oficinas":
           office = str(
                  self.tableOffice.item(self.tableOffice.currentRow(),0).text()                   )
           officecontroller = Office_controller()
           officecontroller.deleteOffice(office)
           self.tableOffice.removeRow(self.tableOffice.currentRow())

    def edit(self):
        comboSelection = self.comboBoxView.currentText()
        if comboSelection == "Hosts":
            current_row = self.tableHost.currentRow()
            host_selected = Host.selectBy(
                        DnsName=str(self.tableHost.item(current_row, 0).text())
                        )
            self.show_edit_host(host_selected[0])
        elif comboSelection == "Templates":
            current_row = self.tableTemplate.currentRow()
            template_selected = Template.selectBy(
                Category = str(self.tableTemplate.item(current_row,0).text())
                )
            self.show_edit_template(template_selected[0])
        elif comboSelection == "Oficinas":
           print "falta agregar el metodo self.show_edit_office()"

    def add(self):
        comboSelection = self.comboBoxView.currentText()
        if comboSelection == "Hosts":
            self.show_add_host()
        elif comboSelection == "Templates":
            self.show_add_template()
        elif comboSelection == "Oficinas":
            self.show_add_office()
    
    def applyChanges(self):
        hosts = Host.select()
        for host in hosts:
            must_have = host.PackagesMustHave()
            may_have = host.PackagesMayHave()
            may_not_have = host.PackagesMayNotHave()
            self.writeToFile(host.DnsName+".MustHave", must_have)
            self.writeToFile(host.DnsName+".MayHave", may_have)
            self.writeToFile(host.DnsName+".MayNotHave", may_not_have)
            self.writeToFile(
                    host.DnsName+".aptRelease",[str(host.Distribution.Name)]
                    )

    def writeToFile(self, filename, list):
        config = configuration()
        path=config.PkgsyncPath
        file = open(path+"/"+str(filename),'w')
        for item in list:
            file.write(item+'\n')
        file.close()
        logModule.log("Generado el archivo "+path+"/"+str(filename))
    
    def refreshPackagesInfo(self):
        apt_db=packages()
        apt_db.refreshPackagesAvaible()

    def show_add_host(self):
        ui = Host_controller()
        ui.widget.exec_()
        self.refresh_table_hosts()
    
    def show_add_distribution(self):
        ui = Distribution_controller()
        ui.widget.exec_()
    
    def show_add_architecture(self):
        ui = Architecture_controller()
        ui.widget.exec_()
    
    def show_add_office(self):
        ui = Office_controller()
        ui.widget.exec_()
        self.refresh_table_offices()

    def show_add_template(self):
        ui = Template_controller()
        ui.widget.exec_()
        self.refresh_table_templates()

    def show_edit_host(self, host):
        ui = Host_controller(host)
        ui.widget.exec_()
        self.refresh_table_hosts()

    def show_edit_office(self, office):
        ui = Office_controller()
        ui.widget.exec_()
        self.refresh_table_offices()

    def show_edit_template(self,template):
        ui = Template_controller(template)
        ui.widget.exec_()
        self.refresh_table_templates()
    
    def add_register_to_table(self, table, row, col, string):
        item=QtGui.QTableWidgetItem()
        item.setText( string )
        table.setItem( row, col, item )
    
    def clean_table(self,table):
        rows = range( table.rowCount()-1 )
        rows.reverse()
        for row in rows:
            table.removeRow(row)

    def refresh_table_offices(self):
        offices = Office.select()
        self.clean_table( self.tableOffice )
        self.tableOffice.setRowCount(offices.count())
        row = 0
        for office in offices:
            self.add_register_to_table( self.tableOffice, row, 0, office.Name )
            self.add_register_to_table( self.tableOffice, row, 1, office.Location )
            self.add_register_to_table( self.tableOffice, row, 2, office.Description )
            self.add_register_to_table( self.tableOffice, row, 3, office.Contact )
            self.add_register_to_table( self.tableOffice, row, 4, office.Phone )
            row = row +1
        self.tableOffice.setCurrentCell(0,0)

    def refresh_table_hosts(self):
        hosts = Host.select()
        self.clean_table( self.tableHost )
        self.tableHost.setRowCount(hosts.count())
        row = 0
        for host in hosts:
            self.add_register_to_table( self.tableHost, row, 0, host.DnsName )
            if type(host.Office) is NoneType:
                self.add_register_to_table(self.tableHost, row, 1, "")
            else:
                self.add_register_to_table( self.tableHost, row, 1, host.Office.Name )
            if type(host.Architecture) is NoneType:
                self.add_register_to_table( self.tableHost, row, 2, "")
            else:
                self.add_register_to_table( self.tableHost, row, 2, host.Architecture.Type )
    
            self.add_register_to_table( self.tableHost, row, 3, host.MacAddress )
            row = row +1 
        self.tableHost.setCurrentCell(0,0)

    def refresh_table_templates(self):
        templates = Template.select()
        self.clean_table( self.tableTemplate )
        self.tableTemplate.setRowCount(templates.count())
        row = 0
        for template in templates:
            self.add_register_to_table( self.tableTemplate, row, 0, template.Category )
            self.add_register_to_table( self.tableTemplate, row, 1, template.Description )
            row = row +1
        self.tableTemplate.setCurrentCell(0,0)

    def change_grid_view(self):
        comboSelection = self.comboBoxView.currentText()               
        self.pushButtonEdit.setEnabled(True)
        if comboSelection == 'Hosts':
            self.tableHost.setVisible(True)
            self.tableTemplate.setVisible(False)
            self.tableOffice.setVisible(False)
            self.refresh_table_hosts()
        elif comboSelection == 'Templates':
            self.tableHost.setVisible(False)
            self.tableTemplate.setVisible(True)
            self.tableOffice.setVisible(False)   
            self.refresh_table_templates()
        else:
            self.tableHost.setVisible(False)
            self.tableTemplate.setVisible(False)
            self.tableOffice.setVisible(True)                                   
            self.refresh_table_offices()
            self.pushButtonEdit.setEnabled(False)
